<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Chinese Chess</title>
</head>

<body>
  <script src="wasm_exec.js"></script>
  <script type="text/javascript" src="jquery/jquery.js"></script>
  <script type="text/javascript" src="vschess/vschess.min.js"></script>
  <script>
    if (!WebAssembly.instantiateStreaming) { // polyfill
      WebAssembly.instantiateStreaming = async (resp, importObject) => {
        const source = await (await resp).arrayBuffer()
        return await WebAssembly.instantiate(source, importObject)
      }
    }

    const go = new Go()
    let mod, inst, chess

    WebAssembly.instantiateStreaming(fetch("index.wasm"), go.importObject).then(async (result) => {
      mod = result.module
      inst = result.instance
      chess = new vschess.load(".vschess", {
        clickResponse: vschess.code.clickResponse.red,
        afterClickAnimate: function () {
          // getAlphaBetaMoveByWasm(this.getCurrentFen())
          getAlphaBetaMoveByApi(this.getCurrentFen())
        }
      })
      await go.run(inst)
      inst = await WebAssembly.instantiate(mod, go.importObject) // reset instance
    })

    async function move(step) {
      console.log('Move with step', step)
      chess.movePieceByNode(step, 75)
    }

    async function getAlphaBetaMoveByApi(fen) {
      $.ajax({
        url: '/best',
        data: { fen: fen },
        type: 'post',
        success: function (response) {
          move(response)
        }
      })
    }
  </script>

  <div style="text-align: center; margin: auto" class="vschess"></div>
</body>

</html>
